package com.hello.pet.service.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.pet.common.enums.UserStatusEnum;
import com.hello.pet.common.exception.BaseException;
import com.hello.pet.service.system.mapper.UserMapper;
import com.hello.pet.service.system.model.User;
import com.hello.pet.service.system.param.UserParam;
import com.hello.pet.service.system.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author hello
 * @since 2022-04-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * security认证登录信息方法
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("name", username));
    }


    /**
     * security认证用户权限方法
     * 每个接口一个标识,通过页面菜单权限(接口权限)配置每个接口对应的key是什么,
     * 然后为每个角色添加多个接口权限,然后角色下的所有人有这些接口权限
     * @param username
     * @return
     */
    @Override
    public Set<String> findPermissions(String username) {
        return baseMapper.getInterfacePermissionsByUserName(username);
    }

    /**
     * 根据openId查询用户
     *
     * @param openId
     */
    @Override
    public User findByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("wx_open_id", openId));
    }

    @Override
    public void addUser(UserParam user) {
        this.addUser(user,null);
    }

    /**
     * 新增用户
     *
     * @param user
     * @param openId
     */
    @Override
    public void addUser(UserParam user, String openId) {
        if (this.checkUserNameIsExist(user.getName())) {
            throw new BaseException("用户名已存在!");
        }
        if (StrUtil.isNotEmpty(user.getPassword())){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        User userBean = BeanUtil.copyProperties(user, User.class);
        userBean.setState(UserStatusEnum.AVAILABLE);
        userBean.setWxOpenId(openId);
        save(userBean);
    }

    /**
     * @param name
     * @return true 存在
     */
    public Boolean checkUserNameIsExist(String name) {
        return BeanUtil.isNotEmpty(this.findByUsername(name));
    }

}